<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getMenuListService, removeMenuService } from '@/apis/acl/menu'
import type { MenuList, MenuListResponseData, Menu } from '@/apis/acl/menu/type'
import AddMenu from './components/addmenu/index.vue'
const menuList = ref<MenuList>([])
const getMenuList = async () => {
  const res: MenuListResponseData = await getMenuListService()
  menuList.value = res.data
}
onMounted(() => getMenuList())

// 添加、修改菜单
const addMenuRef = ref()

const addMenu = (row: Menu) => {
  const newRow = ref({
    id: 0,
    pid: 0,
    name: '',
    code: '',
    level: 0
  })
  newRow.value.pid = row.id as number
  newRow.value.level = (row.level as number) + 1
  addMenuRef.value.open(newRow.value)
}

const updateMenu = (row: Menu) => {
  addMenuRef.value.open(row)
}

const onAddEdit = (val: string) => {
  if (val === 'add') {
    getMenuList()
    ElMessage.success('添加成功')
  } else {
    getMenuList()
    ElMessage.success('修改成功')
  }
}

// 删除menu
const removeMenu = async (id: number) => {
  await ElMessageBox.confirm('确定删除该菜单吗？', '提示', {
    type: 'warning'
  })
  await removeMenuService(id)
  getMenuList()
  ElMessage.success('删除成功')
}
</script>

<template>
  <el-table :data="menuList" row-key="id" border>
    <el-table-column label="名称" prop="name"></el-table-column>
    <el-table-column label="权限值" prop="code"></el-table-column>
    <el-table-column label="修改时间" prop="updateTime"></el-table-column>
    <el-table-column label="操作" width="400px" align="center">
      <template #default="{ row }">
        <el-button
          type="primary"
          icon="Plus"
          round
          :disabled="row.level === 4"
          @click="addMenu(row)"
          >{{ row.level === 3 ? '添加功能' : '添加菜单' }}</el-button
        >
        <el-button
          type="warning"
          icon="Edit"
          round
          @click="updateMenu(row)"
          :disabled="row.level === 1"
          >编辑</el-button
        >
        <el-button
          type="danger"
          @click="removeMenu(row.id)"
          icon="Delete"
          round
          :disabled="row.level === 1"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加、修改菜单 -->
  <AddMenu ref="addMenuRef" @add-edit-menu="onAddEdit"></AddMenu>
</template>
